package models

import (
	"github.com/astaxie/beego/orm"
	"fmt"
)

type DsrUser struct {
	Id         int64
	Account    string
	Password   string
	Name       string //账号名字
	Salt       string //密码盐
	CreateTime int64  //创建时间
}

const adminsql = "dsr_user"

//添加用户
func AdminAdd(a *DsrUser) (int64, error) {
	return orm.NewOrm().Insert(a)
}
//判断用户名是否有重复
func AdminGetByName(loginName string) (*DsrUser, error) {
	a := new(DsrUser)
	err := orm.NewOrm().QueryTable(adminsql).Filter("account", loginName).One(a)
	if err != nil {
		return nil, err
	}
	return a, nil
}

//获取用户列表
func AdminGetList(page, pageSize int, filters ...interface{}) ([]*DsrUser, int64)  {

	offset := (page - 1) * pageSize
	list := make([]*DsrUser, 0)
	query := orm.NewOrm().QueryTable(adminsql)
	//过滤 条件。
	if len(filters) > 0 {
		fmt.Println(filters[0].(string), filters[1])
		for i := 0; i < len(filters); i += 2 {
			query = query.Filter(filters[i].(string), filters[i+1])
		}
	}
	total, _ := query.Count()
	var err error
	if page == -1 {
		_, err = query.OrderBy("id").All(&list)
	} else {
		_, err = query.OrderBy("id").Limit(pageSize, offset).All(&list)
	}
	if err != nil {
		ErrorLog(err)	}
	return list, total

}

func AdminGetById(id int64) (*DsrUser, error) {
	r := new(DsrUser)
	err := orm.NewOrm().QueryTable(adminsql).Filter("id", id).One(r)
	if err != nil {
		return nil, err
	}
	return r, nil
}

func (a *DsrUser) Delete() error {
	if _, err := orm.NewOrm().Delete(a); err != nil {
		return err
	}
	return nil
}

func (a *DsrUser) Update(fields ...string) error {
	if _, err := orm.NewOrm().Update(a, fields...); err != nil {
		return err
	}
	return nil
}